package cloud.lysky.java.on.jvm;

import java.io.FileInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author luoly
 * @describe
 * @date 2022-10-19 15:53
 **/
//自定义类加载器
public class MyClassLoaderTest {
    static class MyClassLoader extends ClassLoader{
        private String classPath;

        public MyClassLoader(String classPath){
            this.classPath = classPath;
        }

        private byte[] loadByte(String name) throws Exception{
            name = name.replaceAll("\\.","/");
            FileInputStream fis = new FileInputStream(classPath + "/" + name + ".class");
            int len = fis.available();
            byte[] data = new byte[len];
            fis.read(data);
            fis.close();
            return data;
        }

        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            try{
                byte[] data = loadByte(name);
                //defineClass将一个字节数组转为Class对象，
                //这个字节数组是class文件读取后最终的字节数组。
                return defineClass(name,data,0,data.length);
            }catch (Exception e){
                e.printStackTrace();
                throw new ClassNotFoundException();
            }
        }
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //初始化自定义类加载器，会先初始化父类ClassLoader，
        //其中会把自定义类加载器的父加载器
        //设置为应用程序类加载器AppClassLoader
        MyClassLoader myClassLoader = new MyClassLoader("D:/test");
        Class<?> aClass = myClassLoader.loadClass("cloud.lysky.java.on.jvm.WaitLoadClass");
        Object o = aClass.getConstructor().newInstance();
        Method print = aClass.getDeclaredMethod("print", null);
        print.invoke(o,null);
        System.out.println(aClass.getClassLoader().getClass().getName());
    }
}